<template>
  <BaseMainSlot>
    <template v-slot:zhactbar>
      <div class="page-top__wrapper">
        <div class="page-top__todo">
          <CommonBtn @click="reload">刷新</CommonBtn>
          <CommonBtn @click="examine">{{ typeText }}提交</CommonBtn>
          <CommonBtn :disabled="!addActive2" @click="add">导入</CommonBtn>
          <CommonBtn :disabled="!delActive" @click="del">删除</CommonBtn>
        </div>
      </div>
    </template>
    <template v-slot:boxleft>
      <div class="zhtabletitle" style="margin: 15px 0px">
        已有{{ typeText }}
        <!-- <CommonBtn class="zhaddbtn" @click="dialogExaminesAddVisible = true">添加</CommonBtn> -->
      </div>
      <el-table v-loading="loading" highlight-current-row :data="tableData" stripe border height="calc(100% - 90px)" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="$utils.selectable" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column v-for="(item, index) in formDatalists" :key="index" :prop="item.prop" :label="item.name" min-width="110" :column-key="`${item.prop}`" :sortable="item.sortable">
          <template v-if="!('index' in scope.row)" slot-scope="scope">
            <span v-if="item.prop === 'enableStatus'">{{ scope.row[item.prop] ? '是' : '否' }}</span>
            <span v-else>{{ scope.row[item.prop] || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100" label="操作">
          <template v-if="scope.row.materialNo" slot-scope="scope">
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small" style="height: 10px" @click="handleDelete(scope.row.materialNo)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
    </template>
    <template v-slot:boxright>
      <div class="zhtabletitle">
        所有{{ typeText }}
        <el-input v-model="materialName" class="w50p" style="margin: 0 10px; width: 30%" :placeholder="'搜索' + typeText + '名称'" clearable @input="searchTwo" />
        <el-cascader
          v-model="cascaderValue"
          :placeholder="'搜索' + typeText + '类型'"
          :options="cascaderList"
          :props="{
            value: 'materialTypeNo',
            label: 'materialTypeName',
            children: 'child',
            multiple: false,
            checkStrictly: true
          }"
          :clearable="true"
          @change="handleChange"
        />
      </div>
      <el-table ref="listData2" v-loading="loadingtwo" highlight-current-row :data="tableDatatwo" stripe border height="calc(100% - 90px)" @selection-change="handleSelectionChangetwo">
        <el-table-column type="selection" :selectable="$utils.selectable" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column v-for="(item, index) in formDatalists.filter(i => i.sort)" :key="index" :prop="item.prop" :label="item.name" min-width="110" :column-key="`${item.prop}`">
          <template v-if="scope.row[`materialNo`] !== undefined" slot-scope="scope">
            <span v-if="item.prop === 'enableStatus'">{{ scope.row[item.prop] ? '是' : '否' }}</span>
            <span v-else>{{ scope.row[item.prop] || '' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page-size="pageSizetwo" :current-page="currentPagetwo" :total-size="totalSizetwo" @changePageSize="changePageSizetwo" @changeCurrentPage="changeCurrentPagetwo" />
    </template>
    <template v-slot:dig>
      <dialogds :visible="dialogExamineFormVisible" @close="close" @titlebtn="titlebtn">
        <template v-slot:form>
          <ExamineForm ref="ExamineForm" v-model="ExamineForm" @sub="savemes" />
          <div style="position: relative;width: 100%;text-align: right;">
            <el-button class="zh-button-two" type="primary" @click="$refs.ExamineForm.sub()">提 交</el-button>
          </div>
        </template>
        <template v-slot:table>
          <el-input v-model="esname" style="margin-bottom: 10px; width: 30%" placeholder="输入名称查询" clearable @input="titlebtn(2)" />
          <el-table class="examineTable" highlight-current-row :data="ExamineTable" stripe border height="calc(100% - 90px)">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column v-for="(item, index) in formDatalists.filter(i => i.sort)" :key="index" :prop="item.prop" :label="item.name" min-width="110">
              <template slot-scope="scope">
                <span v-if="item.prop === 'enableStatus'">{{ scope.row[item.prop] ? '是' : '否' }}</span>
                <span v-else>{{ scope.row[item.prop] || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="原因" min-width="90">
              <template slot-scope="scope">
                {{ scope.row.reason || '————' }}
              </template>
            </el-table-column>
            <el-table-column prop="applyStatus" label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.applyStatus === 1" style="color: yellow; font-weight: 600"> 审核中</span>
                <span v-if="scope.row.applyStatus === 0" style="color: green; font-weight: 600"> 通过</span>
                <span v-if="scope.row.applyStatus === 2" style="color: red; font-weight: 600"> 审核不通过</span>
              </template>
            </el-table-column>
            <el-table-column width="120" label="操作">
              <template slot-scope="scope">
                <el-button class="text-btn-cursor" type="text" :disabled="scope.row.applyStatus !== 1" size="small" style="height: 15px" @click="Examineedit(scope.row)"><i class="el-icon-edit-outline"></i>修 改</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </dialogds>
      <el-dialog title="修改" :visible.sync="dialogExaminesVisible" width="58%">
        <ExamineForm ref="ExamineForms" v-model="ExamineForms" @sub="savees" />
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogExaminesVisible = false">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="$refs.ExamineForms.sub()">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog :title="'添加' + typeText" :visible.sync="dialogExaminesAddVisible" width="58%">
        <ExamineForm ref="ExamineFormAdd" v-model="ExamineFormsAdd" @sub="saveExamine" />
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogExaminesAddVisible = false">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="$refs.ExamineFormAdd.sub()">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import Pagination from '@/components/Pagination';
import nowpagereq from '@/api/processing-management/basic-info-manage/agr-source-base-Manage';
import nowunit from '@/api/basic-info-manage/unit-manage/index.js';
import nowType from '@/api/basic-info-manage/agr-source-Type-Manage/index.js';
import dialogds from '@/views/basic-info-manage/component/dialog.vue';
import BaseMainSlot from '@/components/BaseMainSlot/basezuoyou.vue';
import { mymixin } from '@/utils/mixins';
import { mapGetters } from 'vuex';
import formData from './formData.js';
import ExamineForm from './components/examine-form.vue';
export default {
  components: { Pagination, BaseMainSlot, dialogds, ExamineForm },
  inject: ['reload'],
  mixins: [mymixin],
  props: {
    // 业态
    matType: {
      type: String,
      default: 'rawType'
    }
  },
  data() {
    return {
      examineFormmore: false,
      formDatalists: formData,
      // ----表格二号----
      loadingtwo: true,
      // 当前页
      currentPagetwo: 1,
      // 每页的数据条数
      pageSizetwo: 10,
      // 总条数
      totalSizetwo: 0,
      tableData: [],
      // 表格二号数据
      tableDatatwo: [],
      // 是否能输入
      // -------
      canInput: false,
      rules: {},
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      materialList: [],
      materialTypeList: [],
      materialTypeNo: undefined,
      materialName: undefined,
      dialogExamineFormVisible: false,
      unitList: [],
      unitLists: [],
      unitTypeList: [],
      dialogExaminesVisible: false,
      ExamineForm: {},
      ExamineForms: {},
      ExamineFormsAdd: {},
      cascaderList: [],
      cascaderValue: [],
      cascaderLists: [],
      dialogExaminesAddVisible: false,
      addActive2: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: 'permission/judgePermission'
    }),
    typeText() {
      const { matType } = this;
      let text = '原料';
      if (matType === 'finishProductType') {
        text = '成品';
      }
      if (matType === 'semiProductType') {
        text = '半成品';
      }
      return text;
    }
  },
  watch: {
    dialogExamineFormVisible(v) {
      if (!v) {
        this.examineFormmore = false;
      }
    },
    dialogExaminesAddVisible(v) {
      if (!v) {
        this.$refs['ExamineFormAdd'].resetFields();
      }
    },
    dialogExaminesVisible(v) {
      if (!v) {
        this.$refs['ExamineForms'].resetFields();
      }
    }
  },
  created() {
    this.getSelect();
  },
  mounted() {
    this.getTableDataListone();
  },
  methods: {
    rule(item) {
      return item.isCheck ? this.rules[item.prop] : [{ required: item.required, message: item.name + '不能为空', trigger: ['blur', 'change'] }];
    },
    getTypeData() {
      const { matType } = this;
      if (matType === 'rawType') {
        return {
          rawType: true
        };
      }
      if (matType === 'finishProductType') {
        return {
          finishProductType: true
        };
      }
      if (matType === 'semiProductType') {
        return {
          semiProductType: true
        };
      }
    },
    examine() {
      this.dialogExamineFormVisible = true;
    },
    searchTwo() {
      this.currentPagetwo = 1;
      this.getTableDataListtwo();
    },
    Examineedit(e) {
      this.ExamineForms = { ...e };
      this.dialogExaminesVisible = true;
    },
    savemes(formData) {
      const otherParams = this.getTypeData();
      let param = {
        ...formData,
        ...otherParams,
        applyStatus: 1,
        organizationNo: sessionStorage.organizationNo
      };
      nowpagereq.addListES(param).then(response => {
        let mes = response;
        if (mes.code === 1) {
          this.$message.success('提交成功！');
          this.$refs.ExamineForm.resetFields();
        }
      });
    },
    savees(formData) {
      const otherParams = this.getTypeData();
      let param = {
        ...formData,
        ...otherParams
      };
      nowpagereq.editListES(param).then(response => {
        let mes = response;
        if (mes.code === 1) {
          this.$message.success('修改成功！');
          this.$refs['ExamineForms'].resetFields();
          this.dialogExaminesVisible = false;
          this.titlebtn(2);
        }
      });
    },
    saveExamine(formData) {
      const otherParams = this.getTypeData();
      let param = {
        ...formData,
        ...otherParams
      };
      nowpagereq.materialAdd(param).then(response => {
        let mes = response;
        if (mes.code === 1) {
          this.$message.success('添加成功！');
          this.$refs['ExamineFormAdd'].resetFields();
          this.dialogExaminesAddVisible = false;
          this.search();
        }
      });
    },
    close(e) {
      this.dialogExamineFormVisible = e;
    },
    titlebtn(e) {
      if (e === 2) {
        let params = {
          page: this.currentPage,
          size: this.pageSize,
          unitTypeNo: this.unitTypeNo,
          unitName: this.unitName,
          materialName: this.esname
        };
        nowpagereq.getListES(params).then(response => {
          let mes = response.data;
          if (response.code === 1) {
            this.ExamineTable = mes;
            // this.resetActionBar();
          } else {
            this.$message.warning('获取表格失败');
          }
        });
      }
    },
    // 获取当前拥有类型表格
    getTableDataListone() {
      this.loading = true;
      const otherParams = this.getTypeData();
      const params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...otherParams
        }
      };
      nowpagereq.getFarmingAssetList(params).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error('获取数据失败');
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content.map(i => {
          i.sourceMethodText = i.sourceMethod === '0' ? '自行创建' : '库中导入';
          return i;
        });
        this.addblankmet();
        this.resetActionBar();
        if (res.data.content.length === 0 && this.currentPage !== 1) {
          this.currentPage--;
          this.getTableDataListone();
        }
      });
    },
    // 获取所有物料表格
    getTableDataListtwo(dataItemIdList) {
      const otherParams = this.getTypeData();
      this.loadingtwo = true;
      nowpagereq
        .getAllBasicList({
          page: this.currentPagetwo,
          size: this.pageSizetwo,
          entity: {
            materialTypeNo: this.materialTypeNo,
            materialName: this.materialName,
            materialTypeNoList: dataItemIdList,
            ...otherParams
          }
        })
        .then(res => {
          this.loadingtwo = false;
          if (res.code === 0) {
            this.$message.error('数据获取失败');
          }
          let data = res.data;
          // 赋值总条数
          this.totalSizetwo = data.totalElements;
          // 赋值数组
          this.tableDatatwo = data.content;
          let havline = this.tableDatatwo.length % this.pageSizetwo;
          if (this.tableDatatwo.length < this.pageSizetwo) {
            if (havline < this.pageSizetwo) {
              const remain = this.pageSizetwo - havline;
              for (var i = 0; i < remain; i++) {
                this.tableDatatwo.push({
                  indflag: i + this.tableDatatwo.length - 1
                });
              }
            }
          }

          this.resetActionBar();
        });
    },
    handleChange(value) {
      console.log(value, 'eee', this.cascaderLists);
      this.currentPagetwo = 1;
      if (value.length === 0) {
        this.getTableDataListtwo(this.cascaderLists);
      } else {
        this.getTableDataListtwo(value);
      }
    },
    treeFn(tree, func) {
      tree.forEach(node => {
        func(node);
        node.child && this.treeFn(node.child, func);
      });
    },
    async getSelect() {
      let result = await nowpagereq.getFarmingAssetLists();
      this.cascaderList = result.data;
      this.cascaderLists = [];
      this.treeFn(this.cascaderList, node => {
        this.cascaderLists.push(node.materialTypeNo);
        if (node.child.length === 0) {
          delete node.child;
        }
      });
      this.getTableDataListtwo(this.cascaderLists);
      // const { data: res } = await nowpagereq.getAllBList();
      // this.materialList = res;
      // let arr = [];
      // res.forEach(element => {
      //   arr.push({
      //     materialTypeName: element.materialTypeName,
      //     materialTypeNo: element.materialTypeNo
      //   });
      // });

      // let map = new Map();
      // for (let item of arr) {
      //   if (!map.has(item.materialTypeNo)) {
      //     map.set(item.materialTypeNo, item);
      //   }
      // }
      // this.materialTypeList = [...map.values()];

      // 获取物料类型
      const { data: ress } = await nowType.queryByCondition({});
      this.unitTypeList = ress;
      // 获取数量单位
      const { data: Unit } = await nowunit.getallunitlist({});
      this.unitList = Unit;
      this.formDatalists.forEach((item, index) => {
        if (item.prop === 'materialTypeName') {
          let list = ress.map(el => {
            return { name: el.materialTypeName, value: el.materialTypeNo };
          });
          this.$set(this.formDatalists[index].typeObj, 'list', list);
        }
        if (item.prop === 'unitName') {
          let list = Unit.map(el => {
            return { name: el.unitName, value: el.unitNo };
          });
          this.$set(this.formDatalists[index].typeObj, 'list', list);
        }
      });
    },
    search() {
      this.currentPage = 1;
      this.getTableDataListone();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataListone();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataListone();
    },
    changePageSizetwo(pageSize) {
      this.pageSizetwo = pageSize;
      this.getTableDataListtwo();
    },
    changeCurrentPagetwo(currentPage) {
      this.currentPagetwo = currentPage;
      this.getTableDataListtwo();
    },
    handleSelectionChange(list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map(item => {
        return item.materialNo;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    handleSelectionChangetwo(list) {
      this.nowselectedTwoList = [];
      let lists = list.map(item => {
        if (item.materialNo) {
          return item.materialNo;
        } else {
          return '';
        }
      });
      var r = lists.filter(function(s) {
        return s && s.trim(); // 注：IE9(不包含IE9)以下的版本没有trim()方法
      });
      this.nowselectedTwoList = r;
      if (this.nowselectedTwoList && this.nowselectedTwoList.length > 0) {
        this.addActive2 = true;
      } else this.addActive2 = false;
    },
    del() {
      const list = this.nowselectedList.filter(i => i);
      this.handleDelete(list);
    },
    handleDelete(no) {
      let list = [no];
      if (no instanceof Array) {
        list = no;
      }
      this.$confirm('是否确认删除？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          const { matType } = this;
          let materialType = 'raw';
          if (matType === 'finishProductType') {
            materialType = 'finish';
          }
          if (matType === 'semiProductType') {
            materialType = 'semi';
          }
          nowpagereq.delList(list, materialType).then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功');
              this.getTableDataListone();
            } else {
              this.$message.error('删除失败');
            }
          });
        })
        .catch(action => {});
    },
    add() {
      const { matType } = this;
      let api = null;
      if (matType === 'rawType') {
        api = nowpagereq.addListRaw;
      }
      if (matType === 'finishProductType') {
        api = nowpagereq.addListFinish;
      }
      if (matType === 'semiProductType') {
        api = nowpagereq.addListSemi;
      }
      api(this.nowselectedTwoList).then(res => {
        if (res.code === 1) {
          this.getTableDataListone();
          this.nowselectedTwoList = [];
          this.$refs.listData2.clearSelection();
          this.$message.success('添加成功');
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
  position: relative;
  .zhaddbtn {
    position: absolute;
    right: 0;
    top: -10px;
  }
}

.examineTable {
  ::v-deep ::-webkit-scrollbar-thumb {
    width: 6px;
    background: #ccc;
  }
}
</style>
